package com.wes.dsptest.audioalarm;

import android.media.MediaPlayer;
import android.os.Handler;

import java.io.File;
import java.io.IOException;

public class AudioPlayerUtil {

    private MediaPlayer mediaPlayer = null;
    private IAudioControl control;
    public AudioPlayerUtil(IAudioControl control){
        this.control = control;
    }


    public void createPlayer(String name){
        mediaPlayer = new MediaPlayer();
        try {
            File file = new File(name);
            mediaPlayer.setDataSource(file.getPath());
            mediaPlayer.prepare();
            control.getMaxMusicPosition(mediaPlayer.getDuration());
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
                    startPlayer();
                }
            });
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    control.onComplettion();
                    mediaPlayer.release();
                    handler.removeCallbacks(runnable);
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void setMusicPostion(int pos){
        if(mediaPlayer != null)
        {
            mediaPlayer.seekTo(pos);
        }
    }

    public boolean isHavePlayer()
    {
        if(mediaPlayer != null)
            return true;

        return false;
    }

    public void startPlayer(){
        if(mediaPlayer != null && !mediaPlayer.isPlaying())
        {
            mediaPlayer.start();
            handler.postDelayed(runnable, 500);
        }
    }

    public void stopPlayer()
    {
        if(mediaPlayer != null)
        {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
        mediaPlayer = null;
    }


    public void pausePlayer()
    {
        if(mediaPlayer != null && mediaPlayer.isPlaying())
        {
            mediaPlayer.pause();
        }
    }

    public boolean isPlaying()
    {
        return mediaPlayer.isPlaying();
    }

    private int curPosition;
    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if(mediaPlayer != null){
                curPosition = mediaPlayer.getCurrentPosition();
                control.curPostion(curPosition);
            }
            handler.postDelayed(this, 1000);
        }
    };
}
